import { ElMessage } from 'element-plus'
import axios from 'axios'

let uploadType = null

function install (app) {
  // 上传文件到服务器
  async function uploadFile2Server (file, key, md5, progress) {
    const form = new FormData()
    form.set('File', file)
    form.set('MD5', md5)
    form.set('Key', key)
    const result = await axios.post('/file/upload', form, {
      onUploadProgress: progressEvent => {
        if (progress && typeof progress === 'function') {
          const persent = (progressEvent.loaded / progressEvent.total * 100 | 0)
          progress(persent)
        }
      }
    })
    return result.data.Url
  }

  // 上传文件到七牛
  async function uploadFile2Qiniu () {
    return ''
  }

  async function getUploadType () {
    const result = await axios.get('/open/env')
    return result.data.FileUploadType
  }

  app.config.globalProperties.$uploadFile = async function (file, key, md5, progress) {
    if (!(file instanceof File)) {
      const message = '参数必须是文件 File'
      ElMessage.error(message)
      throw new Error(message)
    }
    // if (uploadType == null) {
    uploadType = await getUploadType()
    // }
    switch (uploadType) {
      case 'LocalFile':
        return await uploadFile2Server(file, key, md5, progress)
      case 'QiniuKoto':
        return await uploadFile2Qiniu()
    }
    // var formData = new FormData();
    const message = '未知的 UploadType，请检查服务器的配置'
    ElMessage.error(message)
    throw new Error(message)
  }
}

export default {
  install
}
